<template>
  <div class="ai-page-container">
    <iframe
      v-if="iframeUrl"
      :src="iframeUrl"
      class="ai-iframe"
      frameborder="0"
      allowfullscreen
      allow="microphone"
    />
    <div v-else class="loading-container">
      <el-loading-directive v-loading="true" text="正在加载AI聊天页面..." />
    </div>
  </div>
</template>

<script setup lang="ts">
import { reportApi } from "@/api/report-api";
import { getToken } from "@/utils/auth";
import { ElMessage } from "element-plus";
import { onMounted, onUnmounted, ref } from "vue";
import { useRouter } from "vue-router";

const router = useRouter();
const baseUrl = "https://paas.stjkj.cn/h5/#/packages/ai/chat";
const iframeUrl = ref("");

// 获取完整的URL，包含token参数
const getFullUrl = () => {
  try {
    const tokenData = getToken();
    if (tokenData && tokenData.accessToken) {
      return `${baseUrl}?token=${tokenData.accessToken}`;
    } else {
      console.warn("未获取到有效的token");
      return baseUrl;
    }
  } catch (error) {
    console.error("获取token失败:", error);
    return baseUrl;
  }
};
// 处理iframe消息
const handleMessage = (event: MessageEvent) => {
  // 验证消息来源
  if (event.origin !== "https://paas.stjkj.cn") {
    return;
  }

  // 检查消息类型
  if (event.data && event.data.type === "view-report") {
    console.log("收到view-report消息:", event.data);

    // 在这里处理您的业务逻辑
    handleViewReport(event.data);
  }
};
// 处理view-report消息的具体逻辑
const handleViewReport = async (data: any) => {
  try {
    console.log("处理view-report数据:", data);

    // 从消息中获取userId
    const userId = data.userId;
    if (!userId) {
      ElMessage.error("未获取到用户ID");
      return;
    }

    // 调用API获取用户最近一次报告
    const response = await reportApi.queryUserLatestReport({
      reportUserId: userId,
      reportType: 1
    });

    if (response.code === 0 && response.data) {
      const reportId = response.data.reportId;

      if (reportId) {
        // 路由跳转到报告详情页面
        router.push({
          path: "/report/detail",
          query: { reportId, mode: "view" }
        });
      } else {
        ElMessage.warning("该用户暂无报告数据");
      }
    } else {
      ElMessage.error(response.message || "获取报告数据失败");
    }
  } catch (error) {
    console.error("处理view-report失败:", error);
    ElMessage.error("获取报告数据失败");
  }
};
onMounted(() => {
  // 组件挂载后设置iframe URL
  iframeUrl.value = getFullUrl();
  // 添加消息监听器
  window.addEventListener("message", handleMessage);
});
onUnmounted(() => {
  // 组件卸载时移除消息监听器
  window.removeEventListener("message", handleMessage);
});
</script>

<style scoped>
.ai-page-container {
  width: 100%;
  height: 100vh;
  position: relative;
  overflow: hidden;
  background-color: #fff;
  border-radius: 12px;
  padding: 24px;
}

.ai-iframe {
  width: 100%;
  height: 100%;
  border: none;
}

.loading-container {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f5f5;
}
</style>
